<!DOCTYPE HTML>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>

  <script type="text/javascript" src="../asset/js/lh.js"></script>
  <script>lh.load()</script>

  <style type="text/css">
    html, body, #app{
      height: 100%;
      margin:0;
    }
    #app{
      padding-left: 200px;
    }

    #chat p{
      margin:0;
    }

    #roomchat p{
      margin:0;
    }
  </style>
</head>

<body>
  <div id="app" class="animate__animated animate__fadeIn">
    <!-- 大厅 -->
    <div v-if="tab=='hall'">
      <div>
        ping:{{ping}}ms，总人数：{{clientCount}}，大厅人数:{{clientCount}}
      </div>

      <div style="margin-top: 20px;height: 100px;overflow-y: auto;">
        玩家列表：<span v-for="v in hall.user">{{v.name}}、</span>
      </div>

      <div style="margin-top: 20px;height: 100px;overflow-y: auto;">
        <p>房间搜索：<input v-model="input.roomSearch"></input></p>
        房间列表：
        <el-button v-for="(v,k) in hall.room" v-show="v.name.indexOf(input.roomSearch)!=-1" @click="enterRoom(k)">
          {{v.name}} {{v.now}}/{{v.num}}
        </el-button>
      </div>

      <div style="margin-top: 20px;">
        聊天：
        <div id="chat" style="height: 200px;overflow-y: auto;">
          <p v-for="v in hall.chat">{{v.name}}:{{v.content}}</p>
        </div>
        发送消息：
        <el-input v-model="input.chat" style="width:500px;" placeholder="回车发送" @keyup.enter.native="chat"></el-input>
      </div>

      <div>
        房间名：
        <input v-model="input.room"></input>
        <el-button @click="setRoom">创建房间</el-button>
      </div>
    </div>

    <!-- 房间 -->
    <div v-if="tab=='room'&&room.user[hall.id]">
      <p v-if="hall.room[room.id]">房间名：{{hall.room[room.id].name}}</p>

      <div style="margin-top: 20px;">
        玩家列表：<span v-for="(v,k) in room.user">{{hall.user[k].name}}({{v.hero}}):{{v.ready?'已准备':'未准备'}}、</span>
      </div>

      <div style="margin-top: 20px;">
        选择英雄：
        <el-select v-model="hero.sel" placeholder="请选择" @change="selHero">
          <el-option v-for="v in hero.list" :label="v" :value="v"></el-option>
        </el-select>
      </div>

      <div style="margin-top: 20px;">
        聊天：
        <div id="roomchat" style="height: 200px;overflow-y: auto;">
          <p v-for="v in room.chat">{{v.name}}:{{v.content}}</p>
        </div>
        发送消息：
        <el-input v-model="input.roomChat" style="width:500px;" placeholder="回车发送" @keyup.enter.native="roomChat"></el-input>
      </div>

      <div style="margin-top: 20px;">
        所有人准备后游戏自动开始
        <el-button v-if="!room.user[hall.id].ready" @click="ready">准备</el-button>
        <el-button v-else @click="unReady">取消准备</el-button>
      </div>
    </div>

    <!-- 菜单 -->
    <loaf-menu ref="menu" @music="changeVolume"></loaf-menu>

    <!-- 背景音乐 -->
    <loaf-music ref="music"></loaf-music>
  </div>

  <script>
    lh.vue({
      data(){
        return{
          name:'',
          save:{},
          tab:'hall',
          server:'',
          ws:null,
          ping:'-',
          allCount:0,
          input:{
            chat:'',
            room:'',
            roomChat:'',
            roomSearch:'',
          },
          hall:{
            id:null,
            user:{},
            room:{},
            chat:[],
          },
          room:{
            id:null,
            user:{},
            chat:[],
            ready:false,
            timer:null,
          },
          hero:{
            list:['步军统帅','龙骑统帅','飞龙统帅'],
            sel:''
          }
        }
      },
      computed:{
        clientCount(){
          let temp=Object.keys(this.hall.user)
          return temp.length
        }
      },
      created(){
        this.server=ipcRenderer.sendSync('getData','server')
        //获取姓名
        this.save=ipcRenderer.sendSync('getData','selSave')
        this.name=this.save.name
        //this.hero.list=[this.name].concat(this.hero.list)

        //连接服务器
        this.connect()
      },
      mounted(){
        this.$refs.music.set('../asset/music/开幕.mp3')
      },
      methods:{
        //准备
        ready(){
          let msg={r:'/room/ready',id:this.hall.id}
          this.ws.send(JSON.stringify(msg))
        },
        //取消准备
        unReady(){
          let msg={r:'/room/unready'}
          this.ws.send(JSON.stringify(msg))
        },
        //发消息
        chat(){
          if(!this.input.chat){
            this.$message.error('请输入消息')
            return
          }
          let msg={r:'/hall/chat',content:this.input.chat}
          //服务器错误的话this.ws.readyState==3
          this.ws.send(JSON.stringify(msg))
          this.input.chat=''
        },
        //房间发消息
        roomChat(){
          if(!this.input.roomChat){
            this.$message.error('请输入消息')
            return
          }
          let msg={r:'/room/chat',content:this.input.roomChat}
          this.ws.send(JSON.stringify(msg))
          this.input.roomChat=''
        },
        //建房
        setRoom(){
          if(!this.input.room){
            this.$message.error('请输入房间名')
            return
          }
          let msg={r:'/hall/room/set',name:this.input.room}
          this.ws.send(JSON.stringify(msg))
          this.room.id=this.hall.id
          this.room.user[this.hall.id]={hero:this.hero.sel,ready:false}
          this.tab='room'
        },
        //加入房间
        enterRoom(id){
          let msg={r:'/room/enter',id:id}
          this.ws.send(JSON.stringify(msg))
        },
        //离开房间
        leaveRoom(){
          let msg={r:'/room/leave'}
          this.ws.send(JSON.stringify(msg))
          this.tab='hall'
          //重置
          if(this.room.timer)clearInterval(this.room.timer)
          this.room.ready=false
          this.room.chat=[]
          this.hero.sel=''
        },
        //选择英雄
        selHero(v){
          let msg={r:'/room/hero',hero:v}
          this.ws.send(JSON.stringify(msg))
        },
        //连接
        connect(){
          this.ws = new WebSocket('ws://'+this.server)
          let timestamp,timer

          this.ws.onopen=(o=>{
            console.log('服务器连接成功')
            //心跳
            timer=setInterval(()=>{
              timestamp = (new Date()).getTime()
              this.ws.send(JSON.stringify({r:'/main/ping'}))
            },10*1000)
            //加入大厅
            let msg={r:'/hall/enter',name:this.name}
            this.ws.send(JSON.stringify(msg))
          })
          this.ws.onmessage=(o=>{
            let res=JSON.parse(o.data)
            //心跳
            if(res.r=='/main/ping'){
              let temp=(new Date()).getTime()
              this.ping=temp-timestamp
              this.allCount=res.data.count
              return
            }
            this.onMsg(res)
          })
          this.ws.onclose=(o=>{
            console.log('onclose')
            console.log(o)
            clearInterval(timer)
            this.$notify({
              title: '提示',
              message: '服务器连接断开',
              duration: 0
            })
          })
          this.ws.onerror=(o=>{
            console.log('onerror')
            console.log(o)
            clearInterval(timer)
            this.$notify({
              title: '提示',
              message: '发生错误，服务器连接断开',
              duration: 0
            })
          })
        },
        onMsg(o){
          //大厅
            //列表 获取ID
            if(o.r=='/hall/list'){
              this.hall.user=o.data.user
              this.hall.room=o.data.room
              this.hall.id=o.data.id
              return
            }
            //有人进入
            if(o.r=='/hall/enter'){
              this.hall.user[o.data.id]={name:o.data.name}
              return
            }
            //有人离开
            if(o.r=='/hall/leave'){
              delete this.hall.user[o.data]
              return
            }
            //发消息
            if(o.r=='/hall/chat'){
              if(this.hall.chat.length>30)this.hall.chat.splice(0,1)
              this.hall.chat.push({name:o.data.name,content:o.data.content})
              this.$nextTick(()=>{
                let chat=document.getElementById('chat')
                chat.scrollTop = chat.scrollHeight
              })
              return
            }
            //建房
            if(o.r=='/hall/room/set'){
              this.hall.room[o.data.id]={
                name:o.data.name,
                now:o.data.now,
                num:o.data.num
              }
              return
            }
            //移除房间
            if(o.r=='/hall/room/del'){
              delete this.hall.room[o.data]
              return
            }
            //房间数据更新
            if(o.r=='/hall/room/update'){
              this.hall.room[o.data.id]=o.data
              return
            }

          //房间
            //你成功加入房间
            if(o.r=='/room/enter/ok'){
              this.room.id=o.data
              this.tab='room'
              return
            }
            //更新你所在房间信息
            if(o.r=='/room/update'){
              this.room.user=o.data.user
              return
            }
            //发消息
            if(o.r=='/room/chat'){
              if(this.room.chat.length>30)this.room.chat.splice(0,1)
              this.room.chat.push({name:o.data.name,content:o.data.content})
              this.$nextTick(()=>{
                let chat=document.getElementById('roomchat')
                chat.scrollTop = chat.scrollHeight
              })
              return
            }
            //游戏倒计时
            if(o.r=='/room/start'){
              //记录数据，进入游戏后发送key、姓名、英雄、人数、房主给服务器
              let owner=this.room.id==this.hall.id?true:false
              let temp={
                key:o.data,
                name:this.name,
                hero:this.hero.sel,
                now:this.hall.room[this.room.id].now,
                num:this.hall.room[this.room.id].num,
                owner:owner
              }
              ipcRenderer.send('setData',['netgame',temp])
              
              //倒计时
              this.room.chat.push({name:'系统',content:'游戏开始倒计时10秒'})
              this.$nextTick(()=>{
                let chat=document.getElementById('roomchat')
                chat.scrollTop = chat.scrollHeight
              })
              let i=9
              this.room.timer=setInterval(()=>{
                this.room.chat.push({name:'系统',content:i})
                this.$refs.music.play('../asset/effect/clock3.mp3')
                this.$nextTick(()=>{
                  let chat=document.getElementById('roomchat')
                  chat.scrollTop = chat.scrollHeight
                })
                //开始游戏
                if(i<=0){
                  clearInterval(this.room.timer)
                  lh.toUrl('game.html?type=net')
                }
                i--
              },1000)
              return
            }
            //取消倒计时
            if(o.r=='/room/unstart'){
              if(this.room.timer){
                this.room.chat.push({name:'系统',content:'有人未准备'})
                this.$nextTick(()=>{
                  let chat=document.getElementById('roomchat')
                  chat.scrollTop = chat.scrollHeight
                })
                clearInterval(this.room.timer)
              }
              return
            }

          //错误信息
          if(o.r=='/main/error'){
            this.$message.error(o.msg)
            return
          }
          //公告
          if(o.r=='/main/notice'){
            this.$notify({title: '通知',message: o.msg,duration: 0})
            return
          }
        },
        changeVolume(type,val){
          if(this.$refs.music)this.$refs.music.volume(type,val)
        }
      }
    })
  </script>
</body>
</html>